package cn.com.wxd.web.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * Created by ComXu on 2017/5/17.
 */
public class WebAppRootListener implements ServletContextListener {

    private static final Logger log = LoggerFactory.getLogger(WebAppRootListener.class);
    private static String realPath;
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        String root = servletContext.getRealPath("/");
        if(root == null) {
            log.error("",new IllegalStateException("不能设置系统属性webApp 目录，在WAR包没有解压前 Spring源码异常:("
                    + "Cannot set web app root system property when WAR file is not expanded)"));
            return;
        } else {
            String param = servletContext.getInitParameter("webAppRootKey");
            String key = param != null?param:"webapp.root";
            String oldValue = System.getProperty(key);
            if(oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
                throw new IllegalStateException("系统属性已经设置为不同的值: \'" + key + "\' = ["
                        + oldValue + "] instead "
                        + "of [" + root + "] - " + "选择唯一的值 \'webAppRootKey\' 配置参数在web.xml中!");
            } else {
                System.setProperty(key, root);
                realPath = root;
                log.info("set web app root system property: \'" + key + "\' = [" + root + "]");
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        if(servletContext == null){
            throw new IllegalArgumentException("ServletContext不能为null");
        }
        String param = servletContext.getInitParameter("webAppRootKey");
        String key = param != null?param:"webapp.root";
        System.getProperties().remove(key);
    }

    /**
     * 获取项目的真实路径
     * @return
     */
    public static String getRealPath(){
        return realPath;
    }
}
